package com.ruoyi.door.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.area.domain.HouseAreaExportT;
import com.ruoyi.area.domain.HouseAreaT;
import com.ruoyi.area.mapper.HouseAreaTMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.data.DataUtils;
import com.ruoyi.data.MD5;
import com.ruoyi.group.domain.HouseGroupT;
import com.ruoyi.group.mapper.HouseGroupTMapper;
import com.ruoyi.purpose.domain.HousePurposeT;
import com.ruoyi.purpose.mapper.HousePurposeTMapper;
import com.ruoyi.setup.domain.HouseSetupT;
import com.ruoyi.setup.mapper.HouseSetupTMapper;
import com.ruoyi.unit.domain.HouseUnitT;
import com.ruoyi.unit.mapper.HouseUnitTMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.door.mapper.HouseDoorTMapper;
import com.ruoyi.door.domain.HouseDoorT;
import com.ruoyi.door.service.IHouseDoorTService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 户管理Service业务层处理
 * 
 * @author lijie
 * @date 2023-04-20
 */
@Service
public class HouseDoorTServiceImpl implements IHouseDoorTService 
{
    @Autowired
    private HouseDoorTMapper houseDoorTMapper;
    @Autowired
    private HousePurposeTMapper housePurposeTMapper;
    @Autowired
    private HouseGroupTMapper houseGroupTMapper;
    @Autowired
    private HouseUnitTMapper houseUnitTMapper;
    @Autowired
    private HouseAreaTMapper houseAreaTMapper;
    @Autowired
    private HouseSetupTMapper houseSetupTMapper;

    /**
     * 查询户管理
     * 
     * @param doorId 户管理主键
     * @return 户管理
     */
    @Override
    public HouseDoorT selectHouseDoorTByDoorId(Long doorId)
    {
        return houseDoorTMapper.selectHouseDoorTByDoorId(doorId);
    }

    @Override
    public HouseDoorT selectHouseDoorAddrByDoorId(Long doorId) {
        return houseDoorTMapper.selectHouseDoorAddrByDoorId(doorId);
    }

    @Override
    public HouseDoorT getDoorT(HouseDoorT houseDoorT) {
        return houseDoorTMapper.getDoorT(houseDoorT);
    }


    /**
     * 查询户管理列表
     * 
     * @param houseDoorT 户管理
     * @return 户管理
     */
    @Override
    public List<HouseDoorT> selectHouseDoorTList(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.selectHouseDoorTList(houseDoorT);
    }

    @Override
    public List<HouseDoorT> selectHouseDoorTList1(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.selectHouseDoorTList(houseDoorT);
    }
	
    @Override
    public List<HouseDoorT> selectHouseDoorReturnList(HouseDoorT houseDoorT) {
        return houseDoorTMapper.selectHouseDoorReturnList(houseDoorT);
    }

    @Override
    public HouseDoorT selectHouseDoorSum(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.selectHouseDoorSum(houseDoorT);
    }

    @Override
    public HouseDoorT selectDoor(HouseDoorT houseDoorT) {
        return houseDoorTMapper.selectDoor(houseDoorT);
    }

    /**
     * 查询计息列表
     *
     * @param houseDoorT 户管理
     * @return 户管理
     */
    @Override
    public List<HouseDoorT> selectHouseRateTList(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.selectHouseRateTList(houseDoorT);
    }

    @Override
    public HouseDoorT selectHouseRateTListSum(HouseDoorT houseDoorT) {
        return houseDoorTMapper.selectHouseRateTListSum(houseDoorT);
    }

    /**
     * 新增户管理
     * 
     * @param houseDoorT 户管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertHouseDoorT(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.insertHouseDoorT(houseDoorT);
    }

    /**
     * 修改户管理
     * 
     * @param houseDoorT 户管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateHouseDoorT(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.updateHouseDoorT(houseDoorT);
    }

    /**
     * 批量删除户管理
     * 
     * @param doorIds 需要删除的户管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHouseDoorTByDoorIds(Long[] doorIds)
    {
        return houseDoorTMapper.deleteHouseDoorTByDoorIds(doorIds);
    }

    /**
     * 删除户管理信息
     *
     * @param doorId 户管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteHouseDoorTByDoorId(Long doorId)
    {
        return houseDoorTMapper.deleteHouseDoorTByDoorId(doorId);
    }

    /**
     * 获取当前户id
     *
     * @return 结果
     */
    @Override
    public int getDoorId()
    {
        return houseDoorTMapper.getDoorId();
    }
    @Override
    public HouseDoorT getBalanceMoneyAll(HouseDoorT houseDoorT)
    {
        return houseDoorTMapper.getBalanceMoneyAll(houseDoorT);
    }

    @Override
    public HouseDoorT getDoorNumber(HouseDoorT houseDoorT) {
        return houseDoorTMapper.getDoorNumber(houseDoorT);
    }

    @Override
    public HouseDoorT getDoorNumber1(HouseDoorT houseDoorT) {
        return houseDoorTMapper.getDoorNumber1(houseDoorT);
    }

    @Override
    public HouseDoorT getBudgetInfo() {
        return houseDoorTMapper.getBudgetInfo();
    }
    @Override
    public HouseDoorT getCostInfo() {
        return houseDoorTMapper.getCostInfo();
    }
    @Override
    public HouseDoorT getUnpaidInfo() {
        return houseDoorTMapper.getUnpaidInfo();
    }
    @Override
    public HouseDoorT getRepairInfo() {
        return houseDoorTMapper.getRepairInfo();
    }


    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Transactional
    @Override
    public String importUser(List<HouseDoorT> userList, Boolean isUpdateSupport, String operName, String areaName ) throws Exception {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 1;
        int num = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        HousePurposeT housePurposeT = new HousePurposeT();
        HouseDoorT houseDoorVo = new HouseDoorT();
        HouseGroupT houseGroupT = new HouseGroupT();
        HouseUnitT houseUnitT = new HouseUnitT();
        HouseSetupT houseSetupT = new HouseSetupT();
        List<HouseDoorT> doorList = new ArrayList<HouseDoorT>();
        List<HouseDoorT> doorList1 = new ArrayList<HouseDoorT>();
        List<HouseGroupT> groupList = new ArrayList<HouseGroupT>();
        List<HouseUnitT> unitList = new ArrayList<HouseUnitT>();
        List<HousePurposeT> purposeList = new ArrayList<HousePurposeT>();
        purposeList = housePurposeTMapper.selectHousePurposeTList(housePurposeT);
        HouseSetupT houseSetupList = houseSetupTMapper.selectHouseSetupTByFeeStandards();
        loop:
        for (HouseDoorT user : userList)
        {
            if(user.getPapersCode()!=null){
                user.setPapersCode(MD5.encrypt(user.getPapersCode()));
            }
            if(user.getTel()!=null){
                user.setTel(MD5.encrypt(user.getTel()));
            }
            if(user.getUserName()!=null){
                user.setUserName(MD5.encrypt(user.getUserName()));
            }
            user.setAreaName(areaName);
            if(doorList1.size()>0){
                for(HouseDoorT houseDoor:doorList1){
                    if(houseDoor.getAreaName().equals(user.getAreaName())&&houseDoor.getGroupName().equals(user.getGroupName())&&houseDoor.getUnitName().equals(user.getUnitName())&&houseDoor.getDoorName().equals(user.getDoorName())){
                        failureNum++;
                        String returnMsg = "第"+(num)+"条数据,"+ user.getAreaName() + "|" + user.getGroupName()  + "|" + user.getUnitName() +  "|" + user.getDoorName() + "该户已存在！";
                        String msg = "<br/>" + returnMsg +  " 导入失败：";
                        successMsg.append(msg);
                        continue  loop;
                    }
                }
            }
            num ++;
            user.setCreateBy(operName);
            if(user.getGroupName().isEmpty()){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,楼房栋号错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            if(user.getUnitName().isEmpty()){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,单元错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            if(user.getDoorName().isEmpty()){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,门号错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            if(user.getPurposeName().isEmpty()){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,用途错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            if(user.getSpace()==null){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,面积错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue;
            }
            if(user.getPrice()==null){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,标准错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue;
            }
            Boolean purposeSts = false;
            for (HousePurposeT vo : purposeList) {
                if (vo.getPurposeName().equals(user.getPurposeName())) {
                    user.setPurposeId(vo.getPurposeId());
                    purposeSts = true;
                }
            }
            if (!purposeSts) {
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,请确认房屋用途！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }


            houseDoorVo.setAreaName(user.getAreaName());
            houseDoorVo.setGroupName(user.getGroupName());
            houseDoorVo.setUnitName(user.getUnitName());
            houseDoorVo.setDoorName(user.getDoorName());
            doorList = houseDoorTMapper.selectHouseDoorTList(houseDoorVo);
            if(doorList.size()>0) {
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,"+ user.getAreaName() + "|" + user.getGroupName()  + "|" + user.getUnitName() +  "|" + user.getDoorName() + "该户已存在！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            houseGroupT.setAreaName(user.getAreaName());
            houseGroupT.setGroupName(user.getGroupName());
            houseGroupT.setCreater(operName);
            groupList = houseGroupTMapper.selectHouseGroupTList(houseGroupT);
            if(groupList.size()==0) {
                houseGroupTMapper.insertHouseGroupT(houseGroupT);
            }
            houseUnitT.setAreaName(user.getAreaName());
            houseUnitT.setGroupName(user.getGroupName());
            houseUnitT.setUnitName(user.getUnitName());
            houseUnitT.setCreater(operName);
            unitList = houseUnitTMapper.selectHouseUnitTList(houseUnitT);
            if(unitList.size()==0) {
                houseUnitTMapper.insertHouseUnitT(houseUnitT);
            }
            if ("1".equals(houseSetupList.getFeeStandards())){
                Double budgetMoney = DataUtils.multiplyTwo(user.getPrice(),user.getSpace());
                user.setBudgetMoney(budgetMoney);
            }else if("2".equals(houseSetupList.getFeeStandards())){
                Double budgetMoney = DataUtils.saveTwoTruncation(user.getPrice()*user.getSpace());
                user.setBudgetMoney(budgetMoney);
            } else if("4".equals(houseSetupList.getFeeStandards())){
                Double budgetMoney = DataUtils.saveOneTruncation(user.getPrice()*user.getSpace());
                user.setBudgetMoney(budgetMoney);
            } else if("3".equals(houseSetupList.getFeeStandards())){
                Double budgetMoney = DataUtils.multiplyOne(user.getPrice(),user.getSpace());
                user.setBudgetMoney(budgetMoney);
            } else if ("5".equals(houseSetupList.getFeeStandards())){
                Double budgetMoney = DataUtils.doubleFloor(user.getPrice()*user.getSpace());
                user.setBudgetMoney(budgetMoney);
            } else {
                Double budgetMoney = DataUtils.intFloor(user.getPrice()*user.getSpace());
                user.setBudgetMoney(budgetMoney);
            }
            int id = houseDoorTMapper.getDoorId();
            String houseId = (DateUtils.dateTimeNow()).substring(2,4) + String.format("%" + 6 + "d", id+1).replace(" ", "0");
            user.setHouseId(houseId);
            user.setCreater(operName);
            user.setRateType("0");
            houseDoorTMapper.insertHouseDoorT(user);
//            if(user.getCostMoney()>0) {
//                houseDoorTMapper.insertCost(user);
//            }
            doorList1.add(user);
            successNum++;
        }
        successMsg.append("导入成功");

        return successMsg.toString();
    }

    @Transactional
    @Override
    public String importUser(List<HouseDoorT> userList, Boolean isUpdateSupport, String operName) throws Exception {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 1;
        int num = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        HousePurposeT housePurposeT = new HousePurposeT();
        HouseDoorT houseDoorVo = new HouseDoorT();
        HouseAreaT houseAreaT = new HouseAreaT();
        HouseGroupT houseGroupT = new HouseGroupT();
        HouseUnitT houseUnitT = new HouseUnitT();
        List<HouseDoorT> doorList = new ArrayList<HouseDoorT>();
        List<HouseDoorT> doorList1 = new ArrayList<HouseDoorT>();
        List<HouseAreaExportT> areaList = new ArrayList<HouseAreaExportT>();
        List<HouseGroupT> groupList = new ArrayList<HouseGroupT>();
        List<HouseUnitT> unitList = new ArrayList<HouseUnitT>();
        List<HousePurposeT> purposeList = new ArrayList<HousePurposeT>();
        purposeList = housePurposeTMapper.selectHousePurposeTList(housePurposeT);
        int id = houseDoorTMapper.getDoorId();
        loop:
        for (HouseDoorT user : userList)
        {
            if(user.getPapersCode()!=null){
                user.setPapersCode(MD5.encrypt(user.getPapersCode()));
            }
            if(user.getTel()!=null){
                user.setTel(MD5.encrypt(user.getTel()));
            }
            if(user.getUserName()!=null){
                user.setUserName(MD5.encrypt(user.getUserName()));
            }


            num ++;
            user.setCreateBy(operName);
            if(user.getAreaName().isEmpty()){
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,小区错误！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
//                user.setAreaName("空");
            }
            if(user.getGroupName().isEmpty()){
//                failureNum++;
//                String returnMsg = "第"+(num)+"条数据,楼房栋号错误！";
//                String msg = "<br/>" + returnMsg +  " 导入失败：";
//                successMsg.append(msg);
//                continue ;
                user.setGroupName("空");
            }
            if(user.getUnitName().isEmpty()){
//                failureNum++;
//                String returnMsg = "第"+(num)+"条数据,单元错误！";
//                String msg = "<br/>" + returnMsg +  " 导入失败：";
//                successMsg.append(msg);
//                continue ;
                user.setUnitName("空");
            }
            if(user.getDoorName().isEmpty()){
//                failureNum++;
//                String returnMsg = "第"+(num)+"条数据,门号错误！";
//                String msg = "<br/>" + returnMsg +  " 导入失败：";
//                successMsg.append(msg);
//                continue ;
                user.setDoorName("空");
            }
            if(user.getSpace()==null){
                user.setSpace(0d);
            }
            Boolean purposeSts = false;
            for (HousePurposeT vo : purposeList) {
                if (vo.getPurposeName().equals(user.getPurposeName())) {
                    user.setPurposeId(vo.getPurposeId());
//                    user.setStandard(DataUtils.multiplyMoney(vo.getBuildMoney(),vo.getPurposeMoney()));
                    purposeSts = true;
                }
            }
            if (!purposeSts) {
                failureNum++;
                String returnMsg = "第"+(num)+"条数据,请确认房屋用途！";
                String msg = "<br/>" + returnMsg +  " 导入失败：";
                successMsg.append(msg);
                continue ;
            }
            houseAreaT.setAreaName(user.getAreaName());
            houseAreaT.setCreater(operName);
            areaList = houseAreaTMapper.selectHouseAreaTList(houseAreaT);
            if(areaList.size()==0) {
                houseAreaTMapper.insertHouseAreaT(houseAreaT);
            }
            houseDoorVo.setAreaName(user.getAreaName());
            houseDoorVo.setGroupName(user.getGroupName());
            houseDoorVo.setUnitName(user.getUnitName());
            houseDoorVo.setDoorName(user.getDoorName());
            doorList = houseDoorTMapper.selectHouseDoorTList(houseDoorVo);
            houseGroupT.setAreaName(user.getAreaName());
            houseGroupT.setGroupName(user.getGroupName());
            houseGroupT.setCreater(operName);
            groupList = houseGroupTMapper.selectHouseGroupTList(houseGroupT);
            if(groupList.size()==0) {
                houseGroupTMapper.insertHouseGroupT(houseGroupT);
            }
            houseUnitT.setAreaName(user.getAreaName());
            houseUnitT.setGroupName(user.getGroupName());
            houseUnitT.setUnitName(user.getUnitName());
            houseUnitT.setCreater(operName);
            unitList = houseUnitTMapper.selectHouseUnitTList(houseUnitT);
            if(unitList.size()==0) {
                houseUnitTMapper.insertHouseUnitT(houseUnitT);
            }

            user.setCreater(operName);
            user.setRateType("0");
            user.setCostSts("1");
            user.setBalance(user.getCostMoney());
            user.setBillNo(DateUtils.dateTimeNowMsec());
            user.setBudgetMoney(user.getCostMoney());
            id++;
            user.setDoorId(Long.valueOf(id));

            if(doorList.size()>0) {
                user.setHouseId(doorList.get(0).getHouseId());
                houseDoorTMapper.updateHouseDoorTByCost(user);
                houseDoorTMapper.insertCost(user);
                continue ;
            }else{
//                String houseId = (DateUtils.dateTimeNow()).substring(2,4) + String.format("%" + 5 + "d", id).replace(" ", "0");
//                user.setHouseId(houseId);
                for(HouseDoorT houseDoor:doorList1){
                    if(houseDoor.getAreaName().equals(user.getAreaName())&&houseDoor.getGroupName().equals(user.getGroupName())&&houseDoor.getUnitName().equals(user.getUnitName())&&houseDoor.getDoorName().equals(user.getDoorName())){
                        doorList1.add(user);
                        houseDoorTMapper.updateHouseDoorTByCost(user);
                        houseDoorTMapper.insertCost(user);
                        continue ;
                    }
                }
                doorList1.add(user);
                houseDoorTMapper.insertHouseDoorT(user);
                houseDoorTMapper.insertCost(user);

            }
            successNum++;


        }

        successMsg.append("<br/> 导入成功");
        return successMsg.toString();
    }
}
